package com.dragon.web.um.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dragon.app.um.service.ClientUserService;
import com.dragon.app.um.vo.JsonResult;
import com.dragon.web.commons.controller.BaseController;
import com.dragon.web.commons.utils.UserUtils;
import com.fintech.common.constant.ErrorCode;
import com.fintech.common.enums.RespStatus;
import com.fintech.common.enums.ReturnCode;
import com.fintech.common.vo.FintechResult;
import com.fintech.third.constant.ResponseResult;
import com.fintech.third.constant.SmsTypeEnum;
import com.fintech.third.model.sms.SmsParameter;
import com.fintech.third.service.sms.SmsService;
import com.fintech.user.entity.RealNameAuthAndFaceCompare;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("${platform.name.code}/clientUser")
public class ClientUserController extends BaseController {
	@Autowired
	private ClientUserService clientUserService;
	
	@Autowired
	private SmsService smsService;
	
	@ResponseBody
	@RequestMapping("valid/account/register")
	public JsonResult<Boolean> validAccountRegister(@RequestBody User user) {
		MarvelsLogUtil.getInstance().info("valid/account/register==>>" + JSONObject.fromObject(user));
		return clientUserService.validAccountRegister(user);
	}
	
	@ResponseBody
	@RequestMapping("sendSmsVerCode")
	public JsonResult<Boolean> sendSmsVerCode(@RequestBody User user) {
		MarvelsLogUtil.getInstance().info("sendSmsVerCode==>>" + JSONObject.fromObject(user));
		SmsParameter param = new SmsParameter();
		ResponseResult responseResult = smsService.sendSms(user.getMobileNo(), param, SmsTypeEnum.LOGIN);
		JsonResult<Boolean> jsonResult = new JsonResult<Boolean>();
		if(StringUtils.equalsIgnoreCase(responseResult.getErrorCode(), ""+RespStatus.SUCCESS.getCode())) {
			jsonResult.setData(Boolean.TRUE);
			jsonResult.setMessage("短信发送成功");
		}else {
			jsonResult.setErrorMsg("短信发送失败");
			jsonResult.setData(Boolean.FALSE);
		}
		return jsonResult;
	}	
	
	@ResponseBody
	@RequestMapping("login")
	public JsonResult<User> login(@RequestBody User user, HttpServletRequest request) {
		MarvelsLogUtil.getInstance().info("clientUser/login===>>" + JSONObject.fromObject(user));
		JsonResult<User> result = new JsonResult<User>();
//		if (StringUtils.isEmpty(user.getDeviceId())) {
//			result.setErrorMsg("缺少设备信息!");
//			return result;
//		}
		// 查看库里面是否存在相同设备ID，如果存在，判断手机号码是否一样，如果不一样，则拒绝登陆（05-11登陆验证需求）
		Map<String, String> headers = this.getHeaders();
		String userAgent = request.getHeader("User-Agent");
		user.setUserAgent(userAgent);
		String ipAddress = getIpAddr();
		return clientUserService.login(user,headers,ipAddress);
	}
	
	@ResponseBody
	@RequestMapping("loginV2")
	public JsonResult<User> loginV2(@RequestBody User user, HttpServletRequest request) {
		MarvelsLogUtil.getInstance().info("clientUser/loginV2===>>" + JSONObject.fromObject(user));
		JsonResult<User> result = new JsonResult<User>();
//		if (StringUtils.isEmpty(user.getDeviceId())) {
//			result.setErrorMsg("缺少设备信息!");
//			return result;
//		}
		// 查看库里面是否存在相同设备ID，如果存在，判断手机号码是否一样，如果不一样，则拒绝登陆（05-11登陆验证需求）
		Map<String, String> headers = this.getHeaders();
		String userAgent = request.getHeader("User-Agent");
		user.setUserAgent(userAgent);
		String ipAddress = getIpAddr();
		return clientUserService.loginV2(user,headers,ipAddress);
	}
	
	/**
	 * 添加实名认证
	 * 
	 * @param realNameAuthentication
	 * @return
	 */
	@ResponseBody
	@RequestMapping("addRealNameAuthentication")
	public JsonResult<String> addRealNameAuthentication(@RequestHeader String idFintechUmUser,
			@RequestHeader String accessToken, @RequestBody RealNameAuthentication realNameAuthentication) {
		MarvelsLogUtil.getInstance().info("addRealNameAuthentication===>>"
				+ com.alibaba.fastjson.JSONObject.toJSONString(realNameAuthentication));
		realNameAuthentication.setPhoto("no url");
		return clientUserService.addRealNameAuthentication(idFintechUmUser, accessToken, realNameAuthentication);
	}
	
	/**
	 * 有盾实名认证和人脸视别入库（只有全部通过后才调用该方法）
	 * 
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "addRealNameAuthAndFaceCompare")
	public FintechResult addRealNameAuthAndFaceCompare(@RequestBody RealNameAuthAndFaceCompare realNameAuthAndFaceCompare, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================实名认证/人脸视别入库==================,参数:" + realNameAuthAndFaceCompare);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientUserService.addRealNameAuthAndFaceCompare(realNameAuthAndFaceCompare, user);
	}
	
	@ResponseBody
	@RequestMapping("registerClient")
	public JsonResult<User> registerClient(@RequestBody User user, HttpServletRequest request) {
		String channelName = request.getHeader("channelName");
		MarvelsLogUtil.getInstance().info("registerClient====>>" + JSONObject.fromObject(user) + "==header>>channelName:" + channelName);
		Map<String, String> headers = this.getHeaders();
		String userAgent = request.getHeader("User-Agent");
		user.setUserAgent(userAgent);
		return clientUserService.registerClient(user, headers, channelName);
	}
	
	/**
	 * 忘记密码
	 * 
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("exchangPwd")
	public JsonResult<User> exchangPwd(@RequestBody User user) {
		MarvelsLogUtil.getInstance().info("exchangPwd====>>" + JSONObject.fromObject(user));
		return clientUserService.exchangPwd(user);
	}
	
	/**
	 * 有盾实名认证和人脸视别调用计费统计（只有状态码为000000,500006,500007,500014才统计）
	 * 
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "addYdCallTimes")
	public FintechResult addYdCallTimes(@RequestBody Map<String, String> map, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==========有盾实名认证/人脸视别调用计费统计==========,参数:" + JSON.toJSONString(map));
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientUserService.addYdCallTimes(map, user);
	}
	
	
	@RequestMapping(value = "verifySlideCode")
	@ResponseBody
	public FintechResult verifySlideCode(@RequestBody Map<String, String> param){
		MarvelsLogUtil.getInstance().info("=======开始滑块验证=============");
		boolean verifySlideCode = false;
		try {
			verifySlideCode = clientUserService.verifySlideCode(param);
			if (!verifySlideCode) {
				return FintechResult.getFailResult(ErrorCode.FAIL, "验证失败");
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("滑块验证异常", e);
			return FintechResult.getFailResult(ErrorCode.FAIL, "验证失败");
		}
		MarvelsLogUtil.getInstance().info("=======结束滑块验证=============结果：" + verifySlideCode);
		return FintechResult.getSuccessResult(verifySlideCode);
	}
	
}
